package com.adminsystem.common.security;

import cn.hutool.json.JSONUtil;
import com.adminsystem.common.utils.JWTUtil;
import com.adminsystem.entity.SysMenu;
import com.adminsystem.entity.SysRole;
import com.adminsystem.entity.SysUser;
import com.adminsystem.service.SysMenuService;
import com.adminsystem.service.SysRoleService;
import com.adminsystem.service.SysUserService;
import com.system.core.http.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        String username = authentication.getName();
        SysUser currentUser = sysUserService.getByUserName(username);
        String token = JWTUtil.getJWTToken(String.valueOf(currentUser.getId()),username);

        List<SysRole> roleList = roleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id=" + currentUser.getId()));
        //遍历所有的角色，获取所有菜单权限而且不重复
        Set<SysMenu> menuCodeSet = new HashSet<>();
        for (SysRole sysRole : roleList) {
            List<SysMenu> menuList = sysMenuService.list(new QueryWrapper<SysMenu>().inSql("id", "select menu_id from sys_role_menu where role_id=" + sysRole.getId()));
            menuCodeSet.addAll(menuList);
        }

        currentUser.setRoles(roleList.stream().map(SysRole::getName).collect(Collectors.joining(",")));
        List<SysMenu> sysMenuList = new ArrayList<>(menuCodeSet);
        //排序
        sysMenuList.sort(Comparator.comparing(SysMenu::getOrderNum));
        //转菜单树
        List<SysMenu> menuList = sysMenuService.buildTreeMenu(sysMenuList);

        var result = new HashMap<String, Object>();
        result.put("token", token);
        result.put("currentUser", currentUser);
        result.put("menuList", menuList);
        result.put("authorityStr", sysUserService.getUserAuthorityInfo(currentUser.getId()));
        outputStream.write(JSONUtil.toJsonStr(R.success("登录成功", result)).getBytes());
        outputStream.flush();
        outputStream.close();
    }
}
